package com.lvmama.service.dw.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import lombok.extern.slf4j.Slf4j;

import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import redis.clients.jedis.JedisCluster;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lvmama.common.constants.Constants;
import com.lvmama.common.result.CodeMessage;
import com.lvmama.common.result.Result;
import com.lvmama.common.utils.EncodeUtil;
import com.lvmama.common.utils.JSONConversionUtil;
import com.lvmama.common.utils.PageInfoUtil;
import com.lvmama.dao.dw.priceStock.PriceDao;
import com.lvmama.dao.dw.priceStock.PriceGatherDao;
import com.lvmama.pojo.dto.dw.PriceDetailQuery;
import com.lvmama.pojo.entity.dw.priceStock.PriceDetail;
import com.lvmama.service.dw.PriceService;

/**
 * @Author:xuzhongwei
 * @Description:价格service
 * @Date：2018/8/6
 */
@Slf4j
@Service("PriceService")
public class PriceServiceImpl implements PriceService {

    @Autowired
    private PriceDao priceDao;

    @Autowired
    private PriceGatherDao priceGatherDao;

    @Autowired
    JedisCluster jedisCluster;
    @Override
    public Result<List<PriceDetail>> selectPriceDetail(PriceDetailQuery query) {
        log.info("selectPriceDetail start, query:" + query);
        try {
        	List<PriceDetail> resultList = null;
            //如果是房型
            if (query.getGroupByBranch()){
            	resultList = priceDao.selectAllPriceDetail(query);
            }else{
            	resultList = priceDao.selectPriceDetail(query);
            }
            return Result.success(resultList);
        } catch (Exception e) {
            log.error("selectPriceDetail error:" + e.getMessage(), e);
            return Result.error(CodeMessage.SERVER_ERROR);
        }
    }

    @Override
    public Result<PageInfo<PriceDetail>> selectPriceDetailPage(PriceDetailQuery query) {
        log.info("selectPriceDetailPage start, query:" + ToStringBuilder.reflectionToString(query, ToStringStyle.DEFAULT_STYLE));
        //设置分页
        List<PriceDetail> PriceDetails = null;
        PageHelper.startPage(query.getCurrentPage(), query.getPageSize());
        try {
            PriceDetails = priceDao.selectPriceDetail(query);
            log.info("selectPriceDetailPage  result:{}", ToStringBuilder.reflectionToString(PriceDetails, ToStringStyle.DEFAULT_STYLE));
            return Result.success(new PageInfo<>(PriceDetails));
        } catch (Exception e) {
            log.error("selectPriceDetailPage error:" + e.getMessage(), e);
            return Result.error(CodeMessage.SERVER_ERROR);
        }
    }

    @Override
    public Result<PageInfo<PriceDetail>> selectAllPriceDetailPage(PriceDetailQuery query) {
    	
        log.info("selectAllPriceDetailPage start, query:" + ToStringBuilder.reflectionToString(query, ToStringStyle.DEFAULT_STYLE));
        List<PriceDetail> PriceDetails = null;
        //设置分页
        PageHelper.startPage(query.getCurrentPage(), query.getPageSize());
        
        try {
            PriceDetails = priceDao.selectAllPriceDetail(query);
            log.info("selectPriceDetailPage  result:{}", ToStringBuilder.reflectionToString(PriceDetails, ToStringStyle.DEFAULT_STYLE));
            return Result.success(new PageInfo<>(PriceDetails));
        } catch (Exception e) {
        	 return Result.error(CodeMessage.SERVER_ERROR);
        }
    }

    @Override
    public Result<List<PriceDetail>> selectPriceGather(PriceDetailQuery query) {

        log.info("selectPriceGather start, query:" + query);
        String key = EncodeUtil.encodePassword(query.toString());
        if (!jedisCluster.exists(key)){
            List<PriceDetail> list = priceGatherDao.selectPriceGather(query);
            jedisCluster.set(key, JSONConversionUtil.objToString(list));
            jedisCluster.expire(key,Constants.TIMEOUT);
        }
        String results = jedisCluster.get(key);
        try {
			List<PriceDetail> resultList = JSONConversionUtil.stringToList(results,PriceDetail.class);
			log.info("selectPriceGather  result:{}", ToStringBuilder.reflectionToString(resultList, ToStringStyle.DEFAULT_STYLE));
			return Result.success(resultList);
        } catch (Exception e) {
            log.error("selectPriceGather error:" + e.getMessage(), e);
            return Result.error(CodeMessage.SERVER_ERROR);
		}
    }

    @Override
    public Result<PageInfoUtil<PriceDetail>> selectPriceGatherPageByRedis(PriceDetailQuery query) {
    	
        log.info("selectPriceGatherPageByRedis start, query:" + ToStringBuilder.reflectionToString(query, ToStringStyle.DEFAULT_STYLE));
        
        try {
	        String key = EncodeUtil.encodePassword(query.toString());
	        long total = jedisCluster.zcard(key);
            if (query.getCurrentPage() == 0) {
                query.setCurrentPage(1);
            }
            int pageStart = (query.getCurrentPage() - 1) * query.getPageSize();
	        int pageEnd = pageStart + query.getPageSize() - 1;
	        //如果total 小于0 表示没有缓存重新加载
	        if (total <= 0){
	            List<PriceDetail>  priceDetails = priceGatherDao.selectPriceGather(query);
	            Map<String, Double> redisMap = new HashMap<>();
	            if (priceDetails != null && priceDetails.size() > 0){
	                double i = 0D;
	                for (PriceDetail priceDetail : priceDetails){
	                    if (priceDetail == null){
	                        continue;
	                    }
	                    String results = JSONConversionUtil.objToString(priceDetail);
	                    redisMap.put(results,i);
	                    i ++;
	                }
	            }
	            total = redisMap.size();
	            jedisCluster.zadd(key, redisMap);
	            jedisCluster.expire(key,Constants.TIMEOUT);
	
	        }
	        Set<String> resultSet = jedisCluster.zrange(key, pageStart, pageEnd);
	        List<PriceDetail> list =  new ArrayList<>();
	        if (resultSet != null && resultSet.size() > 0){
	            for (String detail : resultSet){
	                PriceDetail priceDetail = JSONConversionUtil.stringToObj(detail,PriceDetail.class);
	                if (priceDetail != null){
	                    list.add(priceDetail);
	                }
	            }
	        }
	        log.info("selectPriceGatherPageByRedis  result:{}", ToStringBuilder.reflectionToString(list, ToStringStyle.DEFAULT_STYLE));
	        Result<PageInfoUtil<PriceDetail>> result = Result.success(new PageInfoUtil<>(list, query.getCurrentPage(), query.getPageSize(), total, pageStart, pageEnd));
            return result;
        }catch (Exception e) {
            log.error("selectPriceGather error:" + e.getMessage(), e);
            return Result.error(CodeMessage.SERVER_ERROR);
		}
    }


}
